//
//  XJOAuthController.swift
//  新浪微博
//
//  Created by 徐绩 on 16/4/19.
//  Copyright © 2016年 ayumi. All rights reserved.
//

import UIKit
import SVProgressHUD

let APP_KEY = "3663247462"
let APP_SECRET = "b87e34ba9aefdfcca7e4d0fbaf45862e"
//回调页面
let REDIRECT_URI = "http://www.baidu.com/"

class XJOAuthController: UIViewController {
    
      /*
    App Key：3663247462
    App Secret：b87e34ba9aefdfcca7e4d0fbaf45862e
    */
    
    override func loadView() {
        super.loadView()
        
        //替换控制器的view需要在view加载出来之前替换,所以写在loadview里
        view = webView
        let str = "https://api.weibo.com/oauth2/authorize?client_id=\(APP_KEY)&redirect_uri=\(REDIRECT_URI)"
        
        
        let url = NSURL(string:str)
        let request = NSURLRequest(URL: url!)
        webView.loadRequest(request)
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupUI()
    }
    
    func setupUI(){
        title = "新浪微博"
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "clickClose")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: .Plain, target: self, action: "clickAutoFill")
     
    }
    
    func clickClose(){
    
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    // MARK: - 自动填充
    func clickAutoFill(){
    
        let ayumi = "document.getElementById('userId').value='1009266532@qq.com';document.getElementById('passwd').value='75583282xuji'"
        webView.stringByEvaluatingJavaScriptFromString(ayumi)
        
    }
    
    lazy var webView:UIWebView = {
        
        let webView = UIWebView()
        webView.delegate = self
        return webView
        
    }()

}

// MARK: - 扩展中专门实现webview代理
extension XJOAuthController: UIWebViewDelegate{
    
    //webView将要加载一个请求的时候调用此方法,判断是否要加载这个请求
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        guard let url = request.URL else{
        
            return false
        }
        
        //地址是否以回调页开头,是则返回false
        if url.absoluteString.hasPrefix(REDIRECT_URI){
                //code
            print(url.query)
            
            if let q = url.query where q.containsString("code="){
            
                //截取授权码
                let code = q.substringFromIndex("code=".endIndex)

//                let accountModel = XJUserAccountModel()

//                accountModel.loadAccessToken(code)
                
                //通过code获取token
                XJUserAccountModel.sharedModel.loadAccessToken(code, finished: { (isSuccess) -> () in
                    
                    if isSuccess {
                        
                        self.dismissViewControllerAnimated(false, completion: { () -> Void in
                            
                            //发送通知切换控制器(AppDelegate接收通知,做逻辑处理)
                            NSNotificationCenter.defaultCenter().postNotificationName(XJChangeRootVCNotification, object: nil)
                        })
                    }else{
                        
                        print("登录错误")
                    }
                })
            }
            return false
        }
        
        return true
    }
    
    
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
}

